<template>
	<view class="container">
		<view class="header">
			<view class="user-info">
				<image class="avatar" :src="userInfo.avatar || '/static/images/avatar.png'" mode="aspectFill"></image>
				<view class="welcome">
					<text class="greeting">{{greeting}}，</text>
					<text class="username">{{userInfo.nickname || '测试用户'}}</text>
				</view>
			</view>
			<view class="date-info">
				<text class="date">{{currentDate}}</text>
			</view>
		</view>
		
		<view class="quick-actions">
			<view class="action-item" @click="navigateTo('/pages/record/add')">
				<view class="action-icon bg-blue">
					<text class="iconfont icon-blood"></text>
				</view>
				<text class="action-text">记录血糖</text>
			</view>
			<view class="action-item" @click="navigateTo('/pages/diet/add')">
				<view class="action-icon bg-green">
					<text class="iconfont icon-diet"></text>
				</view>
				<text class="action-text">记录饮食</text>
			</view>
			<view class="action-item" @click="navigateTo('/pages/reminder/index')">
				<view class="action-icon bg-orange">
					<text class="iconfont icon-reminder"></text>
				</view>
				<text class="action-text">设置提醒</text>
			</view>
			<view class="action-item" @click="navigateTo('/pages/articles/list')">
				<view class="action-icon bg-purple">
					<text class="iconfont icon-article"></text>
				</view>
				<text class="action-text">健康阅读</text>
			</view>
		</view>
		
		<view class="blood-sugar-card">
			<view class="card-header">
				<text class="title">今日血糖</text>
				<text class="more" @click="navigateTo('/pages/record/list')">查看更多 ></text>
			</view>
			<view class="card-content">
				<view class="no-data" v-if="!todayRecords.length">
					<image src="/static/images/no-data.png" mode="aspectFit"></image>
					<text>今日暂无血糖记录</text>
					<button class="btn-add" @click="navigateTo('/pages/record/add')">立即记录</button>
				</view>
				<view class="record-list" v-else>
					<view class="record-item" v-for="(item, index) in todayRecords" :key="index">
						<view class="record-time">
							<text class="time">{{item.time}}</text>
							<text class="type">{{item.typeText}}</text>
						</view>
						<view class="record-value" :class="getStatusClass(item.status)">
							{{item.value}}
							<text class="unit">mmol/L</text>
						</view>
					</view>
				</view>
			</view>
		</view>
		
		<view class="health-tips">
			<view class="card-header">
				<text class="title">健康小贴士</text>
			</view>
			<view class="tips-content">
				<text class="tip-text">{{healthTip}}</text>
			</view>
		</view>
		
		<!-- 健康阅读推荐 -->
		<view class="recommended-articles">
			<view class="card-header">
				<text class="title">健康阅读推荐</text>
				<text class="more" @click="navigateTo('/pages/articles/list')">更多文章 ></text>
			</view>
			<view class="articles-content">
				<view class="no-data" v-if="!recommendedArticles.length">
					<text>暂无推荐文章</text>
					<button class="btn-view-more" @click="navigateTo('/pages/articles/list')">浏览全部文章</button>
				</view>
				<swiper v-else class="article-swiper" :indicator-dots="true" indicator-color="rgba(255,255,255,0.4)" indicator-active-color="#8cc9a1" :autoplay="true" :interval="5000" :duration="500" circular>
					<swiper-item v-for="(item, index) in recommendedArticles" :key="index" @click="viewArticle(item)">
						<view class="swiper-article">
							<image :src="item.coverImage || '/static/images/placeholder.png'" class="swiper-image" mode="aspectFill"></image>
							<view class="swiper-overlay">
								<view class="swiper-title">{{ item.title }}</view>
								<view class="swiper-summary">{{ item.summary }}</view>
								<view class="swiper-meta">
									<view class="meta-item">
										<t-icon name="user" size="24rpx" color="#fff"></t-icon>
										<text>{{ item.author }}</text>
									</view>
									<view class="meta-item">
										<t-icon name="browse" size="24rpx" color="#fff"></t-icon>
										<text>{{ item.viewCount || 0 }} 阅读</text>
									</view>
								</view>
							</view>
						</view>
					</swiper-item>
				</swiper>
			</view>
		</view>
		
		<!-- 底部导航栏 -->
		<custom-tabbar></custom-tabbar>
	</view>
</template>

<script>
	import { getUserInfo } from '../../common/utils/auth.js'
	import { getBloodSugarRecords } from '../../common/api/record.js'
	import { getRecommendedArticles, getArticleList } from '../../common/api/article.js'
	import { getBloodSugarStore } from '../../common/utils/store-helper.js'
	
	export default {
		data() {
			return {
				currentDate: '',
				greeting: '你好',
				userInfo: {},
				todayRecords: [],
				healthTip: '保持规律作息，控制饮食，适量运动，是控制血糖的关键。建议每天进行30分钟中等强度的有氧运动，如快走、游泳等。',
				loading: false,
				recommendedArticles: [] // 推荐文章列表
			}
		},
		onLoad() {
			// 设置当前日期
			const now = new Date();
			const year = now.getFullYear();
			const month = now.getMonth() + 1;
			const day = now.getDate();
			this.currentDate = `${year}年${month}月${day}日`;
			
			// 设置问候语
			const hour = now.getHours();
			if (hour < 6) {
				this.greeting = '凌晨好';
			} else if (hour < 9) {
				this.greeting = '早上好';
			} else if (hour < 12) {
				this.greeting = '上午好';
			} else if (hour < 14) {
				this.greeting = '中午好';
			} else if (hour < 17) {
				this.greeting = '下午好';
			} else if (hour < 19) {
				this.greeting = '傍晚好';
			} else {
				this.greeting = '晚上好';
			}
			
			// 获取用户信息
			this.getUserInfo();
			
			// 加载今日血糖记录
			this.loadTodayBloodSugarRecords();
			
			// 加载推荐文章
			this.loadRecommendedArticles();
		},
		onShow() {
			// 每次页面显示时重新获取用户信息和血糖记录，确保数据最新
			this.getUserInfo();
			this.loadTodayBloodSugarRecords();
		},
		methods: {
			// 获取用户信息
			getUserInfo() {
				// 从本地存储获取用户信息
				const userInfo = getUserInfo();
				console.log('获取到的用户信息:', userInfo);
				
				if (userInfo) {
					this.userInfo = userInfo;
				} else {
					// 如果本地没有用户信息，尝试从userProfile获取
					const userProfile = uni.getStorageSync('userProfile');
					if (userProfile) {
						this.userInfo = {
							nickname: userProfile.nickName,
							avatar: userProfile.avatarUrl
						};
						console.log('从userProfile获取用户信息:', this.userInfo);
					}
				}
			},
			
			// 从后端API加载今日血糖记录
			async loadTodayBloodSugarRecords() {
				if (this.loading) return;
				
				this.loading = true;
				
				try {
					// 显示加载中
					uni.showLoading({
						title: '加载中...'
					});
					
					// 请求后端API获取血糖记录
					const res = await getBloodSugarRecords();
					
					// 如果成功获取数据
					if (res.code === 0 && res.data) {
						// 获取当前日期
						const today = new Date().toISOString().slice(0, 10);
						
						// 从响应中提取记录数组
						const records = res.data.records || res.data;
						
						// 处理返回的记录，将数组中的measureTime转为date和time
						const processedRecords = records.map(record => {
							// 如果返回的是measureTime数组，转换为日期和时间字符串
							if (record.measureTime && Array.isArray(record.measureTime)) {
								const [year, month, day, hour, minute] = record.measureTime;
								const paddedMonth = String(month).padStart(2, '0');
								const paddedDay = String(day).padStart(2, '0');
								const paddedHour = String(hour).padStart(2, '0');
								const paddedMinute = String(minute).padStart(2, '0');
								
								return {
									...record,
									date: `${year}-${paddedMonth}-${paddedDay}`,
									time: `${paddedHour}:${paddedMinute}`,
									type: record.measureType === 1 ? 'beforeBreakfast' :
										 record.measureType === 2 ? 'beforeLunch' :
										 record.measureType === 3 ? 'afterBreakfast' : 'random'
								};
							}
							return record;
						});
						
						// 筛选今日记录
						const todayData = processedRecords.filter(item => {
							if (item.date) {
								return item.date === today || item.date.startsWith(today);
							}
							return false;
						});
						
						// 转换数据格式
						this.todayRecords = todayData.map(item => ({
							time: item.time,
							typeText: item.measureTypeText || this.getTypeText(item.type),
							value: parseFloat(item.value).toFixed(1),
							status: item.statusText ? this.getStatusFromText(item.statusText) : this.getStatusByValue(item.value, item.type || item.measureType)
						}));
						
						// 按时间倒序排序，最新记录在前
						this.todayRecords.sort((a, b) => {
							return new Date(`${today} ${b.time}`) - new Date(`${today} ${a.time}`);
						});
						
						console.log('首页获取到今日血糖记录：', this.todayRecords.length);
						
						// 将数据更新到Pinia存储
						const bloodSugarStore = getBloodSugarStore();
						if (bloodSugarStore && bloodSugarStore.setRecords) {
							bloodSugarStore.setRecords(res.data);
						}
					}
				} catch (error) {
					console.error('加载今日血糖记录失败:', error);
					
					// 从Pinia或本地存储尝试获取备份数据
					this.loadFromBackup();
				} finally {
					uni.hideLoading();
					this.loading = false;
				}
			},
			
			// 加载推荐文章
			async loadRecommendedArticles() {
				try {
					console.log('开始加载推荐文章')
					const res = await getRecommendedArticles(3);
					console.log('推荐文章响应:', res)
					
					if (res.code === 0) {
						// 检查返回数据格式
						if (Array.isArray(res.data)) {
							this.recommendedArticles = res.data;
						} else if (res.data.list && Array.isArray(res.data.list)) {
							// 如果返回的是分页数据结构
							this.recommendedArticles = res.data.list;
						} else {
							// 如果没有找到数组，尝试获取第一页文章
							const articlesRes = await getArticleList({page: 1, pageSize: 3});
							if (articlesRes.code === 0 && articlesRes.data.list) {
								this.recommendedArticles = articlesRes.data.list;
							}
						}
						console.log('加载到推荐文章数量:', this.recommendedArticles.length)
					}
				} catch (error) {
					console.error('加载推荐文章失败:', error);
					// 出错时尝试获取第一页文章作为备选
					try {
						const articlesRes = await getArticleList({page: 1, pageSize: 3});
						if (articlesRes.code === 0 && articlesRes.data.list) {
							this.recommendedArticles = articlesRes.data.list;
							console.log('加载到备选文章数量:', this.recommendedArticles.length)
						}
					} catch (e) {
						console.error('加载备选文章也失败:', e);
					}
				}
			},
			
			// 查看文章详情
			viewArticle(article) {
				uni.navigateTo({
					url: `/pages/articles/detail?id=${article.id}`
				});
			},
			
			// 从备份数据加载
			loadFromBackup() {
				try {
					// 尝试从Pinia获取
					const bloodSugarStore = getBloodSugarStore();
					let records = [];
					
					if (bloodSugarStore && bloodSugarStore.records) {
						records = bloodSugarStore.records;
					} else {
						// 从本地存储获取
						records = uni.getStorageSync('bloodSugarRecords') || [];
					}
					
					// 获取当前日期
					const today = new Date().toISOString().slice(0, 10);
					
					// 筛选今日记录
					const todayData = records.filter(item => item.date === today || item.date.startsWith(today));
					
					// 转换数据格式
					this.todayRecords = todayData.map(item => ({
						time: item.time,
						typeText: this.getTypeText(item.type),
						value: item.value.toFixed(1),
						status: this.getStatusByValue(item.value, item.type)
					}));
					
					// 按时间倒序排序
					this.todayRecords.sort((a, b) => {
						return new Date(`${today} ${b.time}`) - new Date(`${today} ${a.time}`);
					});
					
					console.log('从备份数据加载今日血糖记录：', this.todayRecords.length);
				} catch (error) {
					console.error('从备份数据加载今日血糖记录失败:', error);
					this.todayRecords = [];
				}
			},
			
			// 获取测量类型文本
			getTypeText(type) {
				const typeMap = {
					'beforeBreakfast': '空腹',
					'afterBreakfast': '早餐后',
					'beforeLunch': '午餐前',
					'afterLunch': '午餐后',
					'beforeDinner': '晚餐前',
					'afterDinner': '晚餐后',
					'beforeSleep': '睡前',
					'random': '随机'
				};
				return typeMap[type] || type;
			},
			
			// 根据血糖值和测量类型判断状态
			getStatusByValue(value, type) {
				const numValue = parseFloat(value);
				// 如果值不是数字，返回正常
				if (isNaN(numValue)) return 'normal';
				
				// 空腹血糖范围
				if (['beforeBreakfast', 'beforeLunch', 'beforeDinner', 1, 2].includes(type)) {
					if (numValue < 3.9) return 'low';
					if (numValue > 6.1) return 'high';
					return 'normal';
				}
				// 餐后血糖范围
				else if (['afterBreakfast', 'afterLunch', 'afterDinner', 3, 4, 5].includes(type)) {
					if (numValue < 3.9) return 'low';
					if (numValue > 7.8) return 'high';
					return 'normal';
				}
				// 睡前血糖范围
				else if (type === 'beforeSleep' || type === 6) {
					if (numValue < 3.9) return 'low';
					if (numValue > 6.7) return 'high';
					return 'normal';
				}
				// 默认范围
				else {
					if (numValue < 3.9) return 'low';
					if (numValue > 6.1) return 'high';
					return 'normal';
				}
			},
			
			// 根据状态文本获取状态
			getStatusFromText(statusText) {
				if (!statusText) return 'normal';
				
				if (statusText.includes('偏低') || statusText.includes('低血糖')) return 'low';
				if (statusText.includes('偏高') || statusText.includes('高血糖')) return 'high';
				return 'normal';
			},
			
			navigateTo(url) {
				uni.navigateTo({
					url
				});
			},
			getStatusClass(status) {
				switch(status) {
					case 'high':
						return 'text-red';
					case 'low':
						return 'text-orange';
					default:
						return 'text-green';
				}
			}
		}
	}
</script>

<style lang="scss">
.container {
	padding: 30rpx;
	padding-bottom: 150rpx; /* 为底部导航留出空间 */
}

.header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin-bottom: 40rpx;
	
	.user-info {
		display: flex;
		align-items: center;
		
		.avatar {
			width: 100rpx;
			height: 100rpx;
			border-radius: 50%;
			margin-right: 20rpx;
		}
		
		.welcome {
			.greeting {
				font-size: 28rpx;
				color: #666;
			}
			
			.username {
				font-size: 36rpx;
				font-weight: bold;
				color: #333;
			}
		}
	}
	
	.date-info {
		.date {
			font-size: 28rpx;
			color: #666;
		}
	}
}

.quick-actions {
	display: flex;
	justify-content: space-between;
	margin-bottom: 40rpx;
	
	.action-item {
		display: flex;
		flex-direction: column;
		align-items: center;
		width: 22%;
		
		.action-icon {
			width: 100rpx;
			height: 100rpx;
			border-radius: 50%;
			display: flex;
			justify-content: center;
			align-items: center;
			margin-bottom: 10rpx;
			
			.iconfont {
				font-size: 50rpx;
				color: #fff;
			}
		}
		
		.action-text {
			font-size: 26rpx;
			color: #333;
		}
	}
}

.bg-blue {
	background-color: #5e9dff;
}

.bg-green {
	background-color: #8cc9a1;
}

.bg-orange {
	background-color: #ffaa5e;
}

.bg-purple {
	background-color: #a18cff;
}

.blood-sugar-card, .health-tips, .recommended-articles {
	background-color: #fff;
	border-radius: 20rpx;
	padding: 30rpx;
	margin-bottom: 30rpx;
	box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.05);
	
	.card-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 20rpx;
		
		.title {
			font-size: 32rpx;
			font-weight: bold;
			color: #333;
		}
		
		.more {
			font-size: 26rpx;
			color: #8cc9a1;
		}
	}
}

.no-data {
	display: flex;
	flex-direction: column;
	align-items: center;
	padding: 40rpx 0;
	
	image {
		width: 200rpx;
		height: 200rpx;
		margin-bottom: 20rpx;
	}
	
	text {
		font-size: 28rpx;
		color: #999;
		margin-bottom: 30rpx;
	}
	
	.btn-add {
		background-color: #8cc9a1;
		color: #fff;
		font-size: 28rpx;
		padding: 10rpx 40rpx;
		border-radius: 50rpx;
	}
}

.record-list {
	.record-item {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 20rpx 0;
		border-bottom: 1rpx solid #f5f5f5;
		
		&:last-child {
			border-bottom: none;
		}
		
		.record-time {
			.time {
				font-size: 32rpx;
				color: #333;
				margin-right: 20rpx;
			}
			
			.type {
				font-size: 26rpx;
				color: #666;
			}
		}
		
		.record-value {
			font-size: 40rpx;
			font-weight: bold;
			
			.unit {
				font-size: 24rpx;
				font-weight: normal;
				margin-left: 5rpx;
			}
		}
	}
}

.text-green {
	color: #8cc9a1;
}

.text-red {
	color: #ff6b6b;
}

.text-orange {
	color: #ffaa5e;
}

.tips-content {
	padding: 20rpx 0;
	
	.tip-text {
		font-size: 28rpx;
		color: #666;
		line-height: 1.6;
	}
}

/* 推荐文章样式 */
.recommended-articles {
	background-color: #fff;
	border-radius: 20rpx;
	padding: 30rpx;
	margin-bottom: 30rpx;
	box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.05);
	
	.card-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 20rpx;
		
		.title {
			font-size: 32rpx;
			font-weight: bold;
			color: #333;
			position: relative;
			padding-left: 20rpx;
			
			&::before {
				content: '';
				position: absolute;
				left: 0;
				top: 6rpx;
				bottom: 6rpx;
				width: 8rpx;
				background-color: #8cc9a1;
				border-radius: 4rpx;
			}
		}
		
		.more {
			font-size: 26rpx;
			color: #8cc9a1;
		}
	}
	
	.articles-content {
		.article-swiper {
			height: 400rpx;
			border-radius: 16rpx;
			overflow: hidden;
			box-shadow: 0 6rpx 20rpx rgba(0, 0, 0, 0.1);
			
			.swiper-article {
				position: relative;
				width: 100%;
				height: 100%;
				
				.swiper-image {
					width: 100%;
					height: 100%;
					border-radius: 16rpx;
				}
				
				.swiper-overlay {
					position: absolute;
					bottom: 0;
					left: 0;
					right: 0;
					padding: 40rpx 30rpx;
					background: linear-gradient(to bottom, rgba(0,0,0,0) 0%, rgba(0,0,0,0.8) 100%);
					border-radius: 0 0 16rpx 16rpx;
					
					.swiper-title {
						font-size: 34rpx;
						font-weight: bold;
						color: #fff;
						margin-bottom: 16rpx;
						text-shadow: 0 2rpx 4rpx rgba(0,0,0,0.3);
						
						// 最多显示两行
						display: -webkit-box;
						-webkit-line-clamp: 2;
						-webkit-box-orient: vertical;
						overflow: hidden;
					}
					
					.swiper-summary {
						font-size: 26rpx;
						color: rgba(255,255,255,0.8);
						margin-bottom: 16rpx;
						
						// 最多显示两行
						display: -webkit-box;
						-webkit-line-clamp: 2;
						-webkit-box-orient: vertical;
						overflow: hidden;
					}
					
					.swiper-meta {
						display: flex;
						align-items: center;
						
						.meta-item {
							display: flex;
							align-items: center;
							margin-right: 20rpx;
							
							text {
								font-size: 24rpx;
								color: #fff;
								margin-left: 8rpx;
							}
						}
					}
				}
			}
		}
		
		.no-data {
			display: flex;
			flex-direction: column;
			align-items: center;
			padding: 40rpx 0;
			
			text {
				font-size: 28rpx;
				color: #999;
				margin-bottom: 20rpx;
			}
			
			.btn-view-more {
				background-color: #8cc9a1;
				color: #fff;
				font-size: 28rpx;
				padding: 12rpx 40rpx;
				border-radius: 40rpx;
			}
		}
	}
}
</style>

